<template>
  <div class="topic-pick-modal" :style="styleObject">
    <i class="ri-close-fill close" @click="handleCloseModal" v-if="false"></i>
    <p class="title">{{ isSearch ? '主题搜索' : '画布主题锚点选择' }}</p>
    <div class="search-topic-modal">
      <div class="map-list" v-if="!isSearch">
        <p>画布选择</p>
        <el-select v-model="currentMapId" placeholder="青选择画布">
          <el-option
            v-for="item in sheetOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <el-input
        v-model="searchValue"
        placeholder="请输入主题名称搜索"
        :suffix-icon="Search"
        :autofocus="true"
      />
    </div>
    <div class="content-tree">
      <el-tree
        ref="treeRef"
        node-key="_id"
        :data="treeData"
        default-expand-all
        highlight-current
        :props="{ label: 'text', children: 'children', id: '_id' }"
        :filter-node-method="handleFilterTopicNode"
        :expand-on-click-node="false"
        empty-text="主题数据为空"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <div class="node-image-info" v-if="data.imageInfo">
              <img :src="data.imageInfo.url" alt="">
            </div>
            <div class="node-text-info">
              <div class="topic-serial-number" v-if="node.parent?.data?.['child-serial']">{{ generateSerialNumber(node.parent.data['child-serial'], node.parent, data._id) }}</div>
              <div class="node-element-data__markers" v-if="data.marks?.length">
                <div
                  class="mark"
                  v-for="(itemName, idx) in data.marks"
                  :key="itemName.icon"
                  :style="{ left: `${idx * 12}px`, height: '18px' }">
                  <svg width="18" height="18" >
                    <use :xlink:href="`#${itemName.icon}`" />
                  </svg>
                </div>
              </div>
              <p :style="{ 'padding-left': `${data.marks?.length * 12 + 8}px` }">{{ node.label }}</p>
              <div class="latex-span" v-if="data.latex" style="font-size: 10px;" v-html="getLatexHtmlString(data.latex)"></div>
            </div>
          </div>
        </template>
      </el-tree>
    </div>
    <div class="bottom" v-show="!isSearch">
      <el-button type="primary" :disabled="!currentNodeId" @click="handleInsertTopiclink">确 认</el-button>
    </div>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import sequence from '../utils/serialNumber'
import { getLatexHtmlString } from '../utils/katex'

const emits = defineEmits(['anchor-node', 'insert-topiclink', 'close'])
const props = defineProps({
  sheetIdx: Number,
  currentNode: {
    type: Object,
    default: () => null
  }
})
const treeRef = ref()
const searchValue = ref('')
const sheets = JSON.parse(localStorage.getItem('sheets'))
const sheetOptions = ref(sheets.map(o => ({ label: o.name, value: o.id })))
const currentMapId = ref(sheetOptions.value[props.sheetIdx].value)
const treeData = ref([sheets[props.sheetIdx].rootTopic])
const currentNodeId = ref(null)
const isSearch = !props.currentNode

const styleObject = !isSearch ? {
  top: '80px',
  left: '50%',
  bottom: 'none',
  height: '750px',
  width: '450px',
  marginLeft: '-350px',
  padding: '12px'
} : null

const handleFilterTopicNode = (value, data) => {
  if (!value) return true
  return data.text.toLocaleUpperCase().includes(value.toLocaleUpperCase())
}

function handleNodeClick (node) {
  if (currentNodeId.value === node.id) return
  currentNodeId.value = node._id
  if (isSearch) {
    emits('anchor-node', node._id)
  }
}

function generateSerialNumber (childSerialType, parent, id) {
  const brothers = parent.data.children || []
  const idx = brothers.findIndex(o => o._id === id)
  const childSerialTypeSplit = childSerialType.split('-')
  return sequence[childSerialTypeSplit[0]](idx + 1, childSerialTypeSplit[1])
}

function handleInsertTopiclink () {
  emits('insert-topiclink', currentMapId.value, currentNodeId.value)
}

watch(searchValue, (val) => {
  treeRef.value.filter(val)
})

watch(() => currentMapId.value, newVal => {
  treeData.value = [sheets.find(o => o.id === newVal)?.rootTopic]
  currentNodeId.value = null
})

function handleCloseModal () {
  emits('close')
}
</script>

<style lang="scss" scoped>
.topic-pick-modal {
  background-color: #fff;
  box-shadow: 2px 6px 12px 4px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 8px 0 12px;
  position: fixed;
  top: 72px;
  bottom: 70px;
  width: 278px;
  left: 20px;
  display: flex;
  flex-direction: column;
  z-index: 18;
  .title {
    color: #000;
    padding: 0 12px;
    line-height: 38px;
    font-size: 14px;
  }
  .search-topic-modal {
    padding: 0 12px;
    margin-top: 8px;
    .map-list {
      display: flex;
      align-items: center;
      margin: 12px 0 24px;
      p {
        margin-right: 12px;
        color: #999;
        font-size: 13px;
      }
      .el-select {
        flex: 1;
      }
    }
  }
  .content-tree {
    padding: 12px 6px;
    flex: 1;
    height: 0;
    overflow-y: scroll;
    &::-webkit-scrollbar {
      display: none;
    }
    :deep(.el-tree) {
      height: 100%;
      .el-tree-node__content {
        min-height: 34px;
        border-radius: 6px;
        cursor: url('~@/assets/images/default.png' ) 4 4, auto;
        .custom-tree-node {
          flex: 1;
          width: 0;
          display: flex;
          align-items: center;
           user-select: none;
          .node-image-info {
            margin-right: 6px;
            font-size: 0;
            img {
              width: 22px;
              height: 22px;
              object-fit: cover;
              border-radius: 2px;
            }
          }
          .node-text-info {
            flex: 1;
            width: 0;
            color: #333;
            font-size: 13px;
            overflow: hidden;
            white-space: nowrap;
            line-height: 34px;
            text-overflow: ellipsis;
            .node-element-data__markers {
              position: relative;
              .mark {
                position: absolute;
                background: #fff;
                border-radius: 50%;
                top: -1px;
              }
            }
            div, p {
              display: inline;
            }
            .topic-serial-number {
              margin-right: 2px;
            }
          }
        }
        .el-icon {
          color: #333;
          cursor: url('~@/assets/images/default.png' ) 4 4, auto;
        }
      }
    }
  }
  .bottom {
    text-align: right;
  }
  .close {
    position: absolute;
    right: 8px;
    top: 15px;
    font-size: 20px;
    color: #999;
  }
}
</style>
